﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.AuthorCenter.EntityFrameworkCore;
using mozhi.smarterp.AuthorCenter.Permissions.Repositories;
using mozhi.smarterp.AuthorCenter.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.PermissionManagement;

namespace mozhi.smarterp.AuthorCenter.Permissions
{
    public class PermissionItemApiGrantRepository : EfCoreRepository<AuthorCenterDbContext, PermissionItemApiGrant, Guid>, IPermissionItemApiGrantRepository
    {
        public PermissionItemApiGrantRepository(IDbContextProvider<AuthorCenterDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<PermissionItemApiGrant> FindAsync(Guid permissionItemId, Guid apiMetadataId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            return dbContext.Set<PermissionItemApiGrant>().AsNoTracking().FirstOrDefault(x => x.PermissionItemId == permissionItemId && x.ApiMetadataId == apiMetadataId);
        }

        public async Task<long> GetCountAsync(string filter = null, Guid? permissionItemId = null, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<PermissionItemApiGrant>().AsNoTracking()
                .WhereIf(permissionItemId.HasValue, x => x.PermissionItemId == permissionItemId)
                .CountAsync();

            return count;
        }

        public async Task<List<PermissionItemApiGrant>> GetListAsync(string sorting = null, int maxResultCount = int.MaxValue, int skipCount = 0, string filter = null, Guid? permissionItemId = null,
            bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var entities = await dbContext.Set<PermissionItemApiGrant>().AsNoTracking()
                .WhereIf(permissionItemId.HasValue, x => x.PermissionItemId == permissionItemId)
                 .OrderBy<PermissionItemApiGrant>(sorting.IsNullOrWhiteSpace() ? "PermissionItemId" : sorting)
                 .Skip(skipCount * maxResultCount).Take(maxResultCount)
                .ToListAsync();

            return entities;
        }

        public async Task<List<PermissionItemApiGrant>> GetListAsync(List<Guid> permissionItemIds)
        {
            var dbContext = await GetDbContextAsync();

            var entities = await dbContext.Set<PermissionItemApiGrant>().AsNoTracking()
                .Where(x => permissionItemIds.Contains(x.PermissionItemId))
                .ToListAsync();

            return entities;
        }
    }
}
